import {Headers, Http} from '@angular/http';
import {Helper}     from './helper';
import {HTTPService}     from './httpService';
import {HttpExt}     from './HttpExt';

export class Authenticate
{
    tokenTypeKey = "tokenType";
    tokenValueKey = "accessToken";
    tokenAuthorization = "Authorization"

    constructor(private http: HttpExt) {
    }

    setToken(type: any, value:any) {
        sessionStorage.setItem(this.tokenTypeKey, type);
        sessionStorage.setItem(this.tokenValueKey, value);
    }

    setHeaderAuthen(headers: Headers)
    {
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        if (!Helper.IsNull(sessionStorage.getItem(this.tokenTypeKey))) {
            headers.append(this.tokenAuthorization, sessionStorage.getItem(this.tokenTypeKey) + ' ' + sessionStorage.getItem(this.tokenValueKey));
        }
    }

    login(userName:string,pass:string){
        let service: HTTPService;
        service = new HTTPService(this.http);
        let that = this;
        service.post("api/token","grant_type=password&UserName="+userName+"&Password=" + pass, (data) => { 
            that.setToken(data.token_type,data.access_token)
        });
    }
    getExternalProvidersList() {
        let service: HTTPService;
        service = new HTTPService(this.http);
        let that = this;
        service.get("api/account/externalLogins?returnUrl=%2F&generateState=true", null, 
        (data) => { 
            that.getExternalProvidersListCallback(data,that);
        });
    }

    
    getExternalProvidersListCallback(data:any,that:any) {
        var extProviders = jQuery('#extProviders');

        //External Providers auth
        jQuery.each(data, function (key:any, value:any) {
            var img = jQuery('<img/>', {
                src: "../img/" + value.name + ".png"
            });

            var div = jQuery('<div/>', {
                id: "extPr-" + value.name,
                title: value.name + ' authentication',
            });

            div.click((o) => { that.extAuth(value.url) });
            img.appendTo(div);
            div.appendTo(extProviders);
        });
    }

    extAuth(url:string) {
        this.resetToken();

        window.location.href =  url;
    }
    
     resetToken() {
         sessionStorage.removeItem(this.tokenTypeKey);
         sessionStorage.removeItem(this.tokenValueKey);
    }

}

